package com.sky.business.sys.handler.mgr;

import com.sky.business.sys.handler.MqttEventHandler;
import com.sky.business.sys.handler.cmcc.*;
import com.sky.business.sys.handler.exception.NoMatchHandlerException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 凌云平台事件处理器管家
 *
 */
@Component
public class CmccEventHandlerManager implements InitializingBean {

    /**
     * 处理器列表
     */
    private static final List<MqttEventHandler> handlerList = new ArrayList<>();

    @Autowired
    private ForwardToEndpointEventHandler forwardToEndpointEventHandler;

    @Autowired
    private AdjustDeviceInfoEventHandler adjustDeviceInfoEventHandler;

    @Autowired
    private CreateDeviceEventHandler createDeviceEventHandler;

    @Autowired
    private CmccBeginTrackingEventHandler cmccBeginTrackingEventHandler;

    @Autowired
    private CmccEndTrackingEventHandler cmccEndTrackingEventHandler;


    /**
     * 初始化处理器列表
     */
    @Override
    public void afterPropertiesSet()  {
        handlerList.add(createDeviceEventHandler);
        handlerList.add(forwardToEndpointEventHandler);
        handlerList.add(adjustDeviceInfoEventHandler);
        handlerList.add(cmccBeginTrackingEventHandler);
        handlerList.add(cmccEndTrackingEventHandler);
    }

    /**
     * 查找处理器
     * @param topic 主题名
     * @param msg 消息
     * @param event 事件
     * @throws Exception 处理时发生的异常
     */
    @Async("threadPoolTaskExecutor")
    public void handle(String topic, String msg,String event) throws Exception {
        MqttEventHandler handler = handlerList.stream().filter(p -> p.match(topic, msg,event)).findFirst().orElse(null);
        if (handler == null) {
            throw new NoMatchHandlerException("msg:" + msg);
        }
        handler.handle(topic, msg);
    }


}
